package com.study.happystudy.tool;


//import jakarta.websocket.*;
//import jakarta.websocket.server.PathParam;
//import jakarta.websocket.server.ServerEndpoint;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.CopyOnWriteArraySet;
//
//
//@ServerEndpoint(value = "/websocket/{nickname}")
//@Component
//@Slf4j
//public class MyWebsocket {
//    private static Map<String, Session> map = new HashMap<>();
//
//    private static CopyOnWriteArraySet<MyWebsocket> clients = new CopyOnWriteArraySet<>();
//
//    private Session session;
//
//    private String nickname;
//
//    @OnOpen
//    public void onOpen(Session session,@PathParam("roomId") String roomId, @PathParam("nickname") String nickname){
//        this.session = session;
//        this.nickname = nickname;
//
//        clients.add(this);
//        log.info("有新用户加入,当前人数为：", clients.size());
//        this.session.getAsyncRemote().sendText(nickname + "已加入连接,当前人数为：" + clients.size());
//    }
//
//    @OnClose
//    public void onClose(){
//        clients.remove(this);
//        log.info("有用户断开连接,当前人数为：{}", clients.size());
//    }
//
//    @OnMessage
//    public void onMessage(String message, Session session, @PathParam("nickname") String nickname){
//        log.info("来自客户端：{}发来的消息：{}", nickname, message);
//
//        broadcast(nickname + "：" + message);
//    }
//
//    @OnError
//    public void onError(Session session, Throwable error){
//        log.error("出现错误");
//        error.printStackTrace();
//    }
//
//    /**
//     * 自定义群发消息
//     * @param message
//     */
//    public void broadcast(String message){
//        for (MyWebsocket websocket : clients){
//            //异步发送消息
//            websocket.session.getAsyncRemote().sendText(message);
//        }
//    }
//}
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket/{roomId}/{nickname}")
@Component
@Slf4j
public class MyWebsocket {
    private static Map<String, CopyOnWriteArraySet<MyWebsocket>> chatRooms = new ConcurrentHashMap<>();

    private Session session;
    private String nickname;
    private String roomId;

    @OnOpen
    public void onOpen(Session session,  @PathParam("roomId") String roomId, @PathParam("nickname") String nickname){
        this.session = session;
        this.nickname = nickname;
        this.roomId = roomId;

        CopyOnWriteArraySet<MyWebsocket> roomClients = chatRooms.computeIfAbsent(roomId, k -> new CopyOnWriteArraySet<>());
        roomClients.add(this);
        log.info("有新用户加入聊天室 {}, 当前人数为：{}", roomId, roomClients.size());
        this.session.getAsyncRemote().sendText(nickname + " 已加入聊天室 " + roomId + "，当前人数为：" + roomClients.size());
    }

    @OnClose
    public void onClose(){
        CopyOnWriteArraySet<MyWebsocket> roomClients = chatRooms.get(roomId);
        if (roomClients != null) {
            roomClients.remove(this);
            log.info("有用户离开聊天室 {}, 当前人数为：{}", roomId, roomClients.size());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("roomId") String roomId, @PathParam("nickname") String nickname){
        log.info("来自聊天室 {}: 用户 {} 发来的消息：{}", roomId, nickname, message);

        broadcast(nickname + "：" + message, roomId);
    }

    @OnError
    public void onError(Session session, Throwable error){
        log.error("出现错误");
        error.printStackTrace();
    }

    /**
     * 自定义群发消息
     * @param message
     * @param roomId
     */
    public void broadcast(String message, String roomId){
        CopyOnWriteArraySet<MyWebsocket> roomClients = chatRooms.get(roomId);
        if (roomClients != null) {
            for (MyWebsocket websocket : roomClients){
                // 异步发送消息
                websocket.session.getAsyncRemote().sendText(message);
            }
        }
    }
}
